<?php
require_once __DIR__ . '/../config/database.php';

// 获取当前游戏轮次
function getCurrentRound() {
    global $pdo;
    
    $now = date('Y-m-d H:i:s');
    
    // 检查是否有正在进行的轮次
    $stmt = $pdo->prepare("SELECT * FROM game_rounds WHERE end_time > ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$now]);
    $current_round = $stmt->fetch();
    
    if (!$current_round) {
        // 创建新轮次
        $current_round = createNewRound();
    }
    
    return $current_round;
}

// 创建新的游戏轮次
function createNewRound() {
    global $pdo;
    
    // 获取最新轮次号
    $stmt = $pdo->query("SELECT MAX(round_number) as max_round FROM game_rounds");
    $result = $stmt->fetch();
    $new_round_number = ($result['max_round'] ?? 0) + 1;
    
    $start_time = date('Y-m-d H:i:s');
    $end_time = date('Y-m-d H:i:s', strtotime('+15 minutes')); // 10分钟交易 + 5分钟休市
    
    $stmt = $pdo->prepare("INSERT INTO game_rounds (round_number, status, start_time, end_time) VALUES (?, 'trading', ?, ?)");
    $stmt->execute([$new_round_number, $start_time, $end_time]);
    
    $round_id = $pdo->lastInsertId();
    
    // 获取上一轮的结束价格作为新一轮的初始价格
    $initial_price = 100.00; // 默认价格，如果没有上一轮
    
    if ($new_round_number > 1) {
        // 查询上一轮的结束价格
        $stmt = $pdo->prepare("
            SELECT gr.settlement_price, ph.price 
            FROM game_rounds gr 
            LEFT JOIN price_history ph ON ph.round_id = gr.id AND ph.timestamp = (
                SELECT MAX(timestamp) FROM price_history WHERE round_id = gr.id
            )
            WHERE gr.round_number = ?
        ");
        $stmt->execute([$new_round_number - 1]);
        $prev_round = $stmt->fetch();
        
        if ($prev_round) {
            // 优先使用settlement_price，如果没有则使用最后一条价格记录
            $initial_price = $prev_round['settlement_price'] ?: ($prev_round['price'] ?: $initial_price);
            // 获取动态价格区间配置并确保初始价格在区间内
            $price_config = getPriceRangeConfig();
            $initial_price = min($price_config['max_price'], max($price_config['min_price'], $initial_price));
        }
    }
    
    insertPriceHistory($round_id, $initial_price);
    
    return [
        'id' => $round_id,
        'round_number' => $new_round_number,
        'status' => 'trading',
        'start_time' => $start_time,
        'end_time' => $end_time
    ];
}

// 获取轮次状态文本
function getRoundStatusText($status) {
    switch($status) {
        case 'trading': return '交易中';
        case 'settlement': return '结算中';
        case 'break': return '休市中';
        default: return '未知';
    }
}

// 获取用户余额
function getUserBalance($user_id) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $result = $stmt->fetch();
    
    return $result ? $result['balance'] : 0;
}

// 获取用户冻结盈利
function getUserFrozenProfit($user_id) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT frozen_profit FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $result = $stmt->fetch();
    
    return $result ? $result['frozen_profit'] : 0;
}

// 获取用户持仓
function getUserPositions($user_id) {
    global $pdo;
    
    $stmt = $pdo->prepare("
        SELECT up.*, gr.round_number 
        FROM user_positions up 
        JOIN game_rounds gr ON up.round_id = gr.id 
        WHERE up.user_id = ? AND up.is_active = 1 
        ORDER BY up.purchase_time DESC
    ");
    $stmt->execute([$user_id]);
    
    return $stmt->fetchAll();
}

// 获取当前价格
function getCurrentPrice() {
    global $pdo;
    
    $current_round = getCurrentRound();
    
    // 获取最新价格
    $stmt = $pdo->prepare("SELECT price FROM price_history WHERE round_id = ? ORDER BY timestamp DESC LIMIT 1");
    $stmt->execute([$current_round['id']]);
    $result = $stmt->fetch();
    
    if (!$result) {
        // 如果没有价格记录，生成初始价格
        $initial_price = 100.00;
        insertPriceHistory($current_round['id'], $initial_price);
        return $initial_price;
    }
    
    return $result['price'];
}

// 生成新价格（模拟波动）
function generateNewPrice($current_price) {
    global $pdo;
    
    // 检查是否有管理员设置的价格趋势
    $trend = $_SESSION['admin_price_trend'] ?? 'random';
    $strength = $_SESSION['admin_price_strength'] ?? 5;
    
    // 根据趋势和强度调整价格波动范围
    switch ($trend) {
        case 'up':
            // 上涨趋势：波动范围偏向正数
            $min_change = -300 + ($strength * 30); // 强度越大，最小变化越大
            $max_change = 500 + ($strength * 50);  // 强度越大，最大变化越大
            break;
            
        case 'down':
            // 下跌趋势：波动范围偏向负数
            $min_change = -500 - ($strength * 50);  // 强度越大，最小变化越小
            $max_change = 300 - ($strength * 30);   // 强度越大，最大变化越小
            break;
            
        default:
            // 随机趋势：均衡的波动范围
            $min_change = -500;
            $max_change = 500;
    }
    
    // 计算价格变化百分比（除以10000转换为小数）
    $change_percent = (mt_rand($min_change, $max_change) / 10000);
    $new_price = $current_price * (1 + $change_percent);
    
    // 获取动态价格区间配置
    $price_config = getPriceRangeConfig();
    $min_price = $price_config['min_price'];
    $max_price = $price_config['max_price'];
    
    // 确保价格在配置的区间内
    $new_price = max($min_price, min($max_price, $new_price));
    
    // 记录价格生成信息到日志（仅在管理员设置趋势时）
    if ($trend !== 'random') {
        error_log(sprintf(
            "价格生成: %s趋势, 强度%d, 当前价格%.2f, 变化%.2f%%, 新价格%.2f",
            $trend === 'up' ? '上涨' : '下跌',
            $strength,
            $current_price,
            $change_percent * 100,
            round($new_price, 2)
        ));
    }
    
    return round($new_price, 2);
}

// 插入价格历史
function insertPriceHistory($round_id, $price) {
    global $pdo;
    
    $stmt = $pdo->prepare("INSERT INTO price_history (round_id, price) VALUES (?, ?)");
    $stmt->execute([$round_id, $price]);
}

// 获取价格历史
function getPriceHistory($limit = 50) {
    global $pdo;
    
    $current_round = getCurrentRound();
    
    // 确保limit是整数
    $limit = intval($limit);
    
    $stmt = $pdo->prepare("
        SELECT price, timestamp 
        FROM price_history 
        WHERE round_id = ? 
        ORDER BY timestamp DESC 
        LIMIT {$limit}
    ");
    $stmt->execute([$current_round['id']]);
    
    $history = $stmt->fetchAll();
    return array_reverse($history); // 按时间正序返回
}

// 处理买入交易
function processBuyTransaction($user_id, $amount) {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        $current_round = getCurrentRound();
        $current_price = getCurrentPrice();
        
        // 计算3%的交易手续费
        $fee_rate = 0.03;
        $fee = $amount * $fee_rate;
        $actual_amount = $amount - $fee;
        
        // 实际购买数量（扣除手续费后）
        $quantity = $actual_amount / $current_price;
        
        // 检查用户余额
        $user_balance = getUserBalance($user_id);
        if ($user_balance < $amount) {
            throw new Exception('余额不足');
        }
        
        // 检查是否在交易时间内
        $now = time();
        $round_start = strtotime($current_round['start_time']);
        $trading_end = $round_start + (10 * 60); // 10分钟交易时间
        
        if ($now > $trading_end) {
            throw new Exception('交易时间已结束');
        }
        
        // 扣除用户余额
        $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->execute([$amount, $user_id]);
        
        // 创建持仓记录
        $stmt = $pdo->prepare("
            INSERT INTO user_positions (user_id, round_id, round_number, quantity, purchase_price) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([$user_id, $current_round['id'], $current_round['round_number'], $quantity, $current_price]);
        
        // 记录交易
        $stmt = $pdo->prepare("
            INSERT INTO transactions (user_id, round_id, type, quantity, price, amount, fee) 
            VALUES (?, ?, 'buy', ?, ?, ?, ?)
        ");
        $stmt->execute([$user_id, $current_round['id'], $quantity, $current_price, $amount, $fee]);
        
        $transaction_id = $pdo->lastInsertId();
        
        // 处理手续费分成
        processCommission($user_id, $transaction_id, $fee);
        
        $pdo->commit();
        return [
            'success' => true, 
            'message' => '买入成功',
            'fee' => $fee,
            'actual_amount' => $actual_amount,
            'quantity' => $quantity
        ];
        
    } catch (Exception $e) {
        $pdo->rollBack();
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// 处理卖出交易
function processSellTransaction($user_id, $position_id) {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        $current_round = getCurrentRound();
        $current_price = getCurrentPrice();
        
        // 获取持仓信息
        $stmt = $pdo->prepare("SELECT * FROM user_positions WHERE id = ? AND user_id = ? AND is_active = 1");
        $stmt->execute([$position_id, $user_id]);
        $position = $stmt->fetch();
        
        if (!$position) {
            throw new Exception('持仓不存在或已卖出');
        }
        
        // 检查是否在交易时间内
        $now = time();
        $round_start = strtotime($current_round['start_time']);
        $trading_end = $round_start + (10 * 60); // 10分钟交易时间
        
        if ($now > $trading_end) {
            throw new Exception('交易时间已结束');
        }
        
        $gross_sell_amount = $position['quantity'] * $current_price;
        
        // 计算3%的交易手续费
        $fee_rate = 0.03;
        $fee = $gross_sell_amount * $fee_rate;
        $sell_amount = $gross_sell_amount - $fee;
        
        $profit = $sell_amount - ($position['quantity'] * $position['purchase_price']);
        
        // 标记持仓为已卖出
        $stmt = $pdo->prepare("UPDATE user_positions SET is_active = 0 WHERE id = ?");
        $stmt->execute([$position_id]);
        
        // 所有卖出获得的金额（包括本金和盈利，已扣除手续费）都冻结到次日
        $tomorrow = date('Y-m-d', strtotime('+1 day'));
        
        // 冻结总金额（本金 + 盈利 - 手续费）
        $stmt = $pdo->prepare("UPDATE users SET frozen_profit = frozen_profit + ? WHERE id = ?");
        $stmt->execute([$sell_amount, $user_id]);
        
        // 记录每日盈利（包括本金，已扣除手续费）
        $stmt = $pdo->prepare("
            INSERT INTO daily_profits (user_id, profit_amount, earned_date, available_date) 
            VALUES (?, ?, CURDATE(), ?)
        ");
        $stmt->execute([$user_id, $sell_amount, $tomorrow]);
        
        // 记录交易
        $stmt = $pdo->prepare("
            INSERT INTO transactions (user_id, round_id, type, quantity, price, amount, profit, fee) 
            VALUES (?, ?, 'sell', ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$user_id, $current_round['id'], $position['quantity'], $current_price, $gross_sell_amount, $profit, $fee]);
        
        $transaction_id = $pdo->lastInsertId();
        
        // 处理手续费分成
        processCommission($user_id, $transaction_id, $fee);
        
        $pdo->commit();
        return [
            'success' => true, 
            'message' => '卖出成功', 
            'profit' => $profit,
            'fee' => $fee,
            'gross_amount' => $gross_sell_amount,
            'net_amount' => $sell_amount
        ];
        
    } catch (Exception $e) {
        $pdo->rollBack();
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// 解冻到期盈利
function unfreezeAvailableProfits() {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        $today = date('Y-m-d');
        
        // 获取今日可解冻的盈利
        $stmt = $pdo->prepare("
            SELECT user_id, SUM(profit_amount) as total_profit 
            FROM daily_profits 
            WHERE available_date <= ? AND is_available = 0 
            GROUP BY user_id
        ");
        $stmt->execute([$today]);
        $profits = $stmt->fetchAll();
        
        foreach ($profits as $profit) {
            // 将冻结盈利转为可用余额
            $stmt = $pdo->prepare("
                UPDATE users 
                SET balance = balance + ?, frozen_profit = frozen_profit - ? 
                WHERE id = ?
            ");
            $stmt->execute([$profit['total_profit'], $profit['total_profit'], $profit['user_id']]);
            
            // 标记盈利为已解冻
            $stmt = $pdo->prepare("
                UPDATE daily_profits 
                SET is_available = 1 
                WHERE user_id = ? AND available_date <= ? AND is_available = 0
            ");
            $stmt->execute([$profit['user_id'], $today]);
        }
        
        $pdo->commit();
        return true;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("解冻盈利失败: " . $e->getMessage());
        return false;
    }
}

// 更新游戏状态和价格
function updateGameState() {
    global $pdo;
    
    $current_round = getCurrentRound();
    $now = time();
    $round_start = strtotime($current_round['start_time']);
    $trading_end = $round_start + (10 * 60); // 10分钟交易
    $round_end = strtotime($current_round['end_time']); // 15分钟总时长
    
    if ($now <= $trading_end && $current_round['status'] == 'trading') {
        // 交易时间内，更新价格
        $current_price = getCurrentPrice();
        $new_price = generateNewPrice($current_price);
        insertPriceHistory($current_round['id'], $new_price);
        
    } elseif ($now > $trading_end && $now <= $round_end && $current_round['status'] == 'trading') {
        // 进入休市状态
        $final_price = getCurrentPrice();
        $stmt = $pdo->prepare("UPDATE game_rounds SET status = 'break', settlement_price = ? WHERE id = ?");
        $stmt->execute([$final_price, $current_round['id']]);
        
    } elseif ($now > $round_end) {
        // 确保当前轮次有结算价格
        if ($current_round['status'] != 'break' || $current_round['settlement_price'] === null) {
            $final_price = getCurrentPrice();
            $stmt = $pdo->prepare("UPDATE game_rounds SET status = 'break', settlement_price = ? WHERE id = ?");
            $stmt->execute([$final_price, $current_round['id']]);
        }
        
        // 轮次结束，创建新轮次
        createNewRound();
    }
    
    // 解冻到期盈利
    unfreezeAvailableProfits();
}

// 用户注册
function registerUser($username, $password, $invite_code = '') {
    global $pdo;
    
    try {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $inviter_id = null;
        
        // 处理邀请码
        if (!empty($invite_code)) {
            $inviter_stmt = $pdo->prepare("SELECT id FROM users WHERE invite_code = ?");
            $inviter_stmt->execute([$invite_code]);
            $inviter = $inviter_stmt->fetch();
            
            if ($inviter) {
                $inviter_id = $inviter['id'];
            }
        }
        
        // 生成邀请码
        $new_invite_code = strtoupper(substr(md5($username . time()), 0, 8));
        
        $stmt = $pdo->prepare("INSERT INTO users (username, password, inviter_id, invite_code) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $hashed_password, $inviter_id, $new_invite_code]);
        
        return ['success' => true, 'message' => '注册成功' . ($inviter_id ? '，已绑定邀请关系' : '')];
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            return ['success' => false, 'message' => '用户名已存在'];
        }
        return ['success' => false, 'message' => '注册失败'];
    }
}

// 处理手续费分成
function processCommission($user_id, $transaction_id, $fee) {
    global $pdo;
    
    try {
        // 获取用户的邀请人
        $stmt = $pdo->prepare("SELECT inviter_id FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        if (!$user || !$user['inviter_id']) {
            return; // 没有邀请人，无需处理分成
        }
        
        $inviter_id = $user['inviter_id'];
        $commission_rate = 0.40; // 40%分成比例
        $commission_amount = $fee * $commission_rate;
        
        // 记录分成
        $stmt = $pdo->prepare("
            INSERT INTO team_commissions (inviter_id, user_id, transaction_id, commission_rate, commission_amount, original_fee) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$inviter_id, $user_id, $transaction_id, $commission_rate, $commission_amount, $fee]);
        
        // 更新邀请人的累计分成
        $stmt = $pdo->prepare("UPDATE users SET total_commission = total_commission + ? WHERE id = ?");
        $stmt->execute([$commission_amount, $inviter_id]);
        
    } catch (Exception $e) {
        error_log("处理手续费分成失败: " . $e->getMessage());
    }
}

// 用户登录
function loginUser($username, $password) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        return ['success' => true, 'message' => '登录成功'];
    }
    
    return ['success' => false, 'message' => '用户名或密码错误'];
}

// 获取价格区间配置
function getPriceRangeConfig() {
    global $pdo;
    
    $stmt = $pdo->query("SELECT min_price, max_price FROM price_range_config ORDER BY id DESC LIMIT 1");
    $config = $stmt->fetch();
    
    if (!$config) {
        // 如果没有配置，返回默认值
        return ['min_price' => 1.00, 'max_price' => 200.00];
    }
    
    return $config;
}

// 更新价格区间配置
function updatePriceRangeConfig($min_price, $max_price) {
    global $pdo;
    
    // 验证输入
    $min_price = max(0.01, floatval($min_price)); // 最小不能低于0.01
    $max_price = max($min_price + 0.01, floatval($max_price)); // 最大价格必须大于最小价格
    
    try {
        // 检查是否已有配置
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM price_range_config");
        $result = $stmt->fetch();
        
        if ($result['count'] > 0) {
            // 更新现有配置
            $stmt = $pdo->prepare("UPDATE price_range_config SET min_price = ?, max_price = ? ORDER BY id DESC LIMIT 1");
            $stmt->execute([$min_price, $max_price]);
        } else {
            // 插入新配置
            $stmt = $pdo->prepare("INSERT INTO price_range_config (min_price, max_price) VALUES (?, ?)");
            $stmt->execute([$min_price, $max_price]);
        }
        
        return ['success' => true, 'message' => '价格区间配置已更新'];
    } catch (Exception $e) {
        return ['success' => false, 'message' => '更新失败: ' . $e->getMessage()];
    }
}

// 验证密码强度
function validatePasswordStrength($password) {
    $errors = [];
    
    // 长度检查
    if (strlen($password) < 6) {
        $errors[] = '密码长度至少为6位';
    }
    
    if (strlen($password) > 20) {
        $errors[] = '密码长度不能超过20位';
    }
    
    // 检查是否为常见弱密码
    $weak_passwords = ['123456', '123456789', 'password', '12345678', 'qwerty', 'abc123', '111111', '000000'];
    if (in_array(strtolower($password), $weak_passwords)) {
        $errors[] = '密码过于简单，请使用更复杂的密码';
    }
    
    // 检查是否全是数字或全是字母
    if (ctype_digit($password)) {
        $errors[] = '密码不能全是数字';
    }
    
    if (ctype_alpha($password)) {
        $errors[] = '密码不能全是字母';
    }
    
    return $errors;
}

// 记录密码修改日志
function logPasswordChange($user_id, $ip_address = null) {
    global $pdo;
    
    try {
        // 检查表是否存在
        $stmt = $pdo->query("SHOW TABLES LIKE 'password_change_logs'");
        if ($stmt->rowCount() == 0) {
            return; // 表不存在，跳过日志记录
        }
        
        $ip_address = $ip_address ?: $_SERVER['REMOTE_ADDR'] ?? '未知';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '未知';
        
        $stmt = $pdo->prepare("
            INSERT INTO password_change_logs (user_id, change_time, ip_address, user_agent) 
            VALUES (?, NOW(), ?, ?)
        ");
        $stmt->execute([$user_id, $ip_address, $user_agent]);
    } catch (Exception $e) {
        // 日志记录失败不影响主要功能
        error_log("密码修改日志记录失败: " . $e->getMessage());
    }
}

// 修改用户密码
function changeUserPassword($user_id, $old_password, $new_password) {
    global $pdo;
    
    try {
        // 验证输入
        if (empty($old_password) || empty($new_password)) {
            return ['success' => false, 'message' => '密码不能为空'];
        }
        
        // 验证密码强度
        $password_errors = validatePasswordStrength($new_password);
        if (!empty($password_errors)) {
            return ['success' => false, 'message' => $password_errors[0]];
        }
        
        // 检查是否有last_password_change字段
        $has_last_password_change = false;
        try {
            $stmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'last_password_change'");
            $has_last_password_change = $stmt->rowCount() > 0;
        } catch (Exception $e) {
            // 忽略错误，继续执行
        }
        
        // 获取用户信息
        if ($has_last_password_change) {
            $stmt = $pdo->prepare("SELECT username, password, last_password_change FROM users WHERE id = ?");
        } else {
            $stmt = $pdo->prepare("SELECT username, password FROM users WHERE id = ?");
        }
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            return ['success' => false, 'message' => '用户不存在'];
        }
        
        // 验证旧密码
        if (!password_verify($old_password, $user['password'])) {
            return ['success' => false, 'message' => '当前密码错误'];
        }
        
        // 检查新密码是否与旧密码相同
        if (password_verify($new_password, $user['password'])) {
            return ['success' => false, 'message' => '新密码不能与当前密码相同'];
        }
        
        // 检查是否频繁修改密码（仅在有相关字段时检查）
        if ($has_last_password_change && isset($user['last_password_change']) && $user['last_password_change']) {
            $last_change = new DateTime($user['last_password_change']);
            $now = new DateTime();
            $interval = $now->diff($last_change);
            
            if ($interval->h < 1 && $interval->days == 0) {
                return ['success' => false, 'message' => '修改密码过于频繁，请稍后再试'];
            }
        }
        
        // 开始事务
        $pdo->beginTransaction();
        
        try {
            // 加密新密码
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            // 更新密码和最后修改时间
            if ($has_last_password_change) {
                $stmt = $pdo->prepare("UPDATE users SET password = ?, last_password_change = NOW() WHERE id = ?");
                $stmt->execute([$hashed_password, $user_id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_password, $user_id]);
            }
            
            // 记录密码修改日志
            logPasswordChange($user_id);
            
            // 提交事务
            $pdo->commit();
            
            return ['success' => true, 'message' => '密码修改成功'];
            
        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => '修改失败: ' . $e->getMessage()];
    }
}

// 获取历史轮次列表
function getHistoryRounds($limit = 50, $filter = 'today') {
    global $pdo;
    
    // 验证并限制limit参数
    $limit = intval($limit);
    if ($limit <= 0) $limit = 50;
    if ($limit > 1000) $limit = 1000; // 防止查询过多数据
    
    $where_clause = '';
    $params = [];
    
    switch ($filter) {
        case 'today':
            // 只显示今天的轮次
            $where_clause = 'WHERE DATE(start_time) = CURDATE()';
            break;
        case 'yesterday':
            // 只显示昨天的轮次
            $where_clause = 'WHERE DATE(start_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
            break;
        case 'week':
            // 显示最近7天的轮次
            $where_clause = 'WHERE start_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)';
            break;
        case 'month':
            // 显示最近30天的轮次
            $where_clause = 'WHERE start_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
            break;
        case 'all':
        default:
            // 显示所有轮次（默认行为）
            $where_clause = '';
            break;
    }
    
    $sql = "
        SELECT 
            id,
            round_number,
            status,
            start_time,
            end_time,
            settlement_price
        FROM game_rounds 
        {$where_clause}
        ORDER BY round_number DESC 
        LIMIT " . $limit;
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    return $stmt->fetchAll();
}

// 获取指定轮次的K线数据
function getRoundKlineData($round_id) {
    global $pdo;
    
    // 获取轮次信息
    $stmt = $pdo->prepare("SELECT * FROM game_rounds WHERE id = ?");
    $stmt->execute([$round_id]);
    $round = $stmt->fetch();
    
    if (!$round) {
        return null;
    }
    
    // 获取该轮次的价格历史数据
    $stmt = $pdo->prepare("
        SELECT 
            price,
            timestamp
        FROM price_history 
        WHERE round_id = ? 
        ORDER BY timestamp ASC
    ");
    $stmt->execute([$round_id]);
    $price_data = $stmt->fetchAll();
    
    if (empty($price_data)) {
        return [
            'round' => $round,
            'kline_data' => [],
            'summary' => [
                'open' => 0,
                'close' => 0,
                'high' => 0,
                'low' => 0,
                'volume' => 0
            ]
        ];
    }
    
    // 按时间分组生成K线数据（每分钟一根K线）
    $kline_data = [];
    $current_minute = '';
    $minute_data = [];
    
    foreach ($price_data as $data) {
        $timestamp = $data['timestamp'];
        $price = floatval($data['price']);
        $minute = date('Y-m-d H:i', strtotime($timestamp));
        
        if ($current_minute !== $minute) {
            // 如果有上一分钟的数据，生成K线
            if (!empty($minute_data)) {
                $kline_data[] = generateKlineCandle($current_minute, $minute_data);
            }
            
            // 开始新的一分钟
            $current_minute = $minute;
            $minute_data = [$price];
        } else {
            $minute_data[] = $price;
        }
    }
    
    // 处理最后一分钟的数据
    if (!empty($minute_data)) {
        $kline_data[] = generateKlineCandle($current_minute, $minute_data);
    }
    
    // 计算整轮汇总数据
    $all_prices = array_column($price_data, 'price');
    $summary = [
        'open' => floatval($price_data[0]['price']),
        'close' => floatval(end($price_data)['price']),
        'high' => max($all_prices),
        'low' => min($all_prices),
        'volume' => count($price_data)
    ];
    
    return [
        'round' => $round,
        'kline_data' => $kline_data,
        'summary' => $summary
    ];
}

// 生成单根K线蜡烛图数据
function generateKlineCandle($time, $prices) {
    return [
        'time' => $time,
        'open' => $prices[0],
        'close' => end($prices),
        'high' => max($prices),
        'low' => min($prices),
        'volume' => count($prices)
    ];
}

// 获取轮次交易统计
function getRoundTradingStats($round_id) {
    global $pdo;
    
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_trades,
            SUM(CASE WHEN type = 'buy' THEN 1 ELSE 0 END) as buy_trades,
            SUM(CASE WHEN type = 'sell' THEN 1 ELSE 0 END) as sell_trades,
            SUM(amount) as total_volume,
            AVG(price) as avg_price,
            MIN(price) as min_price,
            MAX(price) as max_price
        FROM transactions 
        WHERE round_id = ?
    ");
    $stmt->execute([$round_id]);
    
    $stats = $stmt->fetch();
    
    return $stats ?: [
        'total_trades' => 0,
        'buy_trades' => 0,
        'sell_trades' => 0,
        'total_volume' => 0,
        'avg_price' => 0,
        'min_price' => 0,
        'max_price' => 0
    ];
}

// 获取某天所有轮次的K线数据（每根K线代表一轮）
function getDailyRoundsKlineData($date = null) {
    global $pdo;
    
    if ($date === null) {
        $date = date('Y-m-d');
    }
    
    // 获取指定日期的所有轮次
    $stmt = $pdo->prepare("
        SELECT 
            id,
            round_number,
            start_time,
            end_time,
            status,
            settlement_price
        FROM game_rounds 
        WHERE DATE(start_time) = ? 
        ORDER BY start_time ASC
    ");
    $stmt->execute([$date]);
    $rounds = $stmt->fetchAll();
    
    if (empty($rounds)) {
        return [
            'date' => $date,
            'kline_data' => [],
            'summary' => [
                'total_rounds' => 0,
                'avg_open' => 0,
                'avg_close' => 0,
                'high' => 0,
                'low' => 0
            ]
        ];
    }
    
    $kline_data = [];
    $all_opens = [];
    $all_closes = [];
    $all_highs = [];
    $all_lows = [];
    
    foreach ($rounds as $round) {
        // 获取该轮次的价格历史数据
        $stmt = $pdo->prepare("
            SELECT 
                price,
                timestamp
            FROM price_history 
            WHERE round_id = ? 
            ORDER BY timestamp ASC
        ");
        $stmt->execute([$round['id']]);
        $price_data = $stmt->fetchAll();
        
        if (empty($price_data)) {
            continue; // 跳过没有价格数据的轮次
        }
        
        // 计算该轮次的OHLC数据
        $prices = array_column($price_data, 'price');
        $open_price = floatval($price_data[0]['price']);
        $close_price = floatval(end($price_data)['price']);
        $high_price = max($prices);
        $low_price = min($prices);
        
        // 生成该轮次的K线数据
        $kline_data[] = [
            'round_id' => $round['id'],
            'round_number' => $round['round_number'],
            'time' => date('H:i', strtotime($round['start_time'])), // 显示开始时间
            'start_time' => $round['start_time'],
            'end_time' => $round['end_time'],
            'status' => $round['status'],
            'open' => $open_price,
            'close' => $close_price,
            'high' => $high_price,
            'low' => $low_price,
            'volume' => count($price_data),
            'settlement_price' => $round['settlement_price']
        ];
        
        // 收集汇总数据
        $all_opens[] = $open_price;
        $all_closes[] = $close_price;
        $all_highs[] = $high_price;
        $all_lows[] = $low_price;
    }
    
    // 计算汇总统计
    $summary = [
        'total_rounds' => count($kline_data),
        'avg_open' => !empty($all_opens) ? array_sum($all_opens) / count($all_opens) : 0,
        'avg_close' => !empty($all_closes) ? array_sum($all_closes) / count($all_closes) : 0,
        'high' => !empty($all_highs) ? max($all_highs) : 0,
        'low' => !empty($all_lows) ? min($all_lows) : 0
    ];
    
    return [
        'date' => $date,
        'kline_data' => $kline_data,
        'summary' => $summary
    ];
}
?>
